package com.sunlake.spring.main.common.model.pay.mq.consumer;

import com.rabbitmq.client.Channel;
import com.sunlake.spring.main.model.account.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 支付消息消费者
 * 负责接收和处理支付相关的消息
 * @author liuha
 */
@Component
@Slf4j
public class PayMessageConsumer {

    @Autowired
    private AccountService accountService;

    /**
     * 监听支付队列的消息
     * 设置ackMode为MANUAL以使用手动确认模式
     */
    @RabbitListener(queues = "pay.queue", ackMode = "MANUAL")
    public void handlePayMessage(Map<String, Object> message, Channel channel, Message amqpMessage) throws IOException, IOException {
        long deliveryTag = amqpMessage.getMessageProperties().getDeliveryTag();
        try {
            log.info("接收到支付消息：{}", message);

            // 根据消息类型分发到不同的处理方法
            if (message.containsKey("createTime")) {
                // 处理订单创建消息
                processOrderCreate(message);
            } else if (message.containsKey("tradeStatus")) {
                // 处理支付结果消息
                processPayResult(message);
            }

            // 确认消息已消费
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("处理支付消息异常：{}，消息内容：{}", e.getMessage(), message);
            // 对于不可恢复的错误，将消息发送到死信队列
            channel.basicNack(deliveryTag, false, false);
        }
    }

    /**
     * 处理订单创建消息
     */
    private void processOrderCreate(Map<String, Object> message) {
        String outTradeNo = (String) message.get("outTradeNo");
        String totalAmount = (String) message.get("totalAmount");
        String subject = (String) message.get("subject");

        log.info("处理订单创建：订单号={}, 金额={}, 商品={}", outTradeNo, totalAmount, subject);

        // TODO: 实现订单持久化逻辑
    }
    /**
     * 处理支付结果消息
     */
    private void processPayResult(Map<String, Object> message) {
        String outTradeNo = (String) message.get("outTradeNo");
        String tradeStatus = (String) message.get("tradeStatus");
        String transactionNo = (String) message.get("transactionNo");  // 从消息中获取交易号

        log.info("处理支付结果：订单号={}, 支付状态={}, 交易号={}", outTradeNo, tradeStatus, transactionNo);

        // 当支付成功时更新用户余额
        if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
            try {
                boolean result = accountService.updateBalanceAfterPayment(outTradeNo, transactionNo);
                if (result) {
                    log.info("支付成功，已更新用户余额，订单号：{}", outTradeNo);
                } else {
                    log.error("更新用户余额失败，订单号：{}", outTradeNo);
                }
            } catch (Exception e) {
                log.error("调用更新余额服务异常：", e);
                // 此处可以考虑发送到死信队列或进行其他处理
            }
        }
        // TODO: 实现更新订单支付状态的逻辑
    }
}